package utils;

import book.Book;
import com.bit.utils.FileUtils;

import java.io.IOException;
import java.time.LocalDateTime;

import static Constant.constant.FILE_NAME;

//用于存储每本书的状态
public class AnalyzingBook {
    //用于存储书籍数据的
    public void storeBook(Book[] books,String filename) throws IOException {
        //先遍历出Book数组中真实到底有多少个书籍
        int bookNum = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i] != null) {
                bookNum++;
            }
        }
        //for循环后得到总共有多少本书
        //再将信息以字符串的形式存储
        StringBuilder stringBooks = new StringBuilder();
        for (int i = 0; i < bookNum; i++) {
            if(books[i]!=null) {
                stringBooks.append(books[i].tostring());
                if(i != bookNum-1) {
                    stringBooks.append("\n");
                }
            }
        }
        //将stringBooks字符串写入文件中
        FileUtils.writeFile(stringBooks.toString(),filename);
    }

    //用于读取文件内容,将其变成书籍对象
    public Book[] loadBook(String filename) throws IOException {
        //1、从文件中读取数据
        String content = FileUtils.readFile(filename);
        //判断图书是否为空
        if(content == null || content.isEmpty()) {
            System.out.println("图书馆没有图书！");
            return null;
        }

        //2、解析出Book对象，以\n分割数据，存储到数组里面
        String[] bookstr = content.split("\n");

        //3、把对应字符串“组装”成书籍对象

        Book[] bookList = new Book[bookstr.length];
        for (int i = 0; i < bookList.length; i++) {
            bookList[i] = parseBookString(bookstr[i]);
        }
        return bookList;
    }
    //将每本书的信息进行拆分，创建每本书的对象
    private Book parseBookString(String string) {
        //分割得到书籍的每个信息
        String[] pairs = string.split(",");
        //将每个属性进行赋值
        int number = Integer.parseInt(pairs[0]);
        String title = pairs[1];
        String author = pairs[2];
        String category = pairs[3];
        int publishYear = Integer.parseInt(pairs[4]);
        Boolean isBorrowed = Boolean.parseBoolean(pairs[5]);
        int borrowCount = Integer.parseInt(pairs[6]);
        LocalDateTime shelfDate = LocalDateTime.parse(pairs[7]);
        //构造书籍对象
        Book book = new Book(title,author,category,publishYear,shelfDate);
        book.setBorrowed(isBorrowed);
        book.setBorrowCount(borrowCount);
        book.setNumber(number);
        return book;
    }
}
